package cn.gaozhong.org.service.impl;

import cn.gaozhong.basic.service.impl.BaseServiceImpl;
import cn.gaozhong.org.domain.Department;
import cn.gaozhong.org.mapper.DepartmentMapper;
import cn.gaozhong.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service

public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }
    @Transactional
    @Override
    public void update(Department department) {
        //取id
        Long id = department.getId();
        String dirPath = "";
        if (department.getParent()!=null){
            //取到父级的dirPath
            dirPath = departmentMapper.loadById(department.getParent().getId()).getDirPath();

        }
        //然后父级dirPath用/拼接自己的id
        department.setDirPath(dirPath+"/"+id);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {
        //查询所有数据
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department > all = new HashMap<>();
        for (Department department : departments) {
            all.put(department.getId(),department);
        }
        
        List<Department> list = new ArrayList<>();
        for (Department temp : departments) {
            if (temp.getParent_id()==null){
                //找到所有第一级层
                list.add(temp);
            }else{
                //只要不是一级就找到上级 存入上级的children中
                Department parent = all.get(temp.getParent_id());
                if (parent!=null){
                    parent.getChildren().add(temp);
                }

            }
        }

        return list;
    }


}
